package IO;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * @author wuhan
 * @date 2019/10/13 15:35
 */

class Read implements Runnable{

    private PipedInputStream in;

    public Read(PipedInputStream in) {
        this.in = in;
    }

    @Override
    public void run() {
        byte[] buf=new byte[1024];
        try {
            System.out.println("读取前没有数据就阻塞");
            int len=in.read(buf);
            String s =new String(buf,0,len);
            System.out.println(s);
            in.close();
            System.out.println("读到数据，阻塞结束");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Write implements Runnable{
    private PipedOutputStream out;

    public Write(PipedOutputStream out) {
        this.out = out;
    }

    @Override
    public void run() {
        try {
            try {
                System.out.println("6秒后写入数据");
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            out.write("piped lai la".getBytes());
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}




public class PipedDemo {
    public static void main(String[] args) throws IOException {
        PipedInputStream in=new PipedInputStream();
        PipedOutputStream out=new PipedOutputStream();
        in.connect(out);
        Read r=new Read(in);
        Write w=new Write(out);
        new Thread(r).start();
        new Thread(w).start();
    }

}
